﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Castle.Core.Logging;

namespace TVN.ShopMan.ApplicationInterface.AppForms
{
    using TVN.Common.Interfaces;
    using TVN.ShopMan.ActiveModels;
    using TVN.ShopMan.ApplicationInterface.Helpers;

    public partial class UnitFormEdit : Form
    {
        private static readonly ILogger _logger = Program.Logger.CreateChildLogger("UnitFormEdit");
        private IRepository<Unit> unitRepository = null;
        private Unit selectedUnit = null;

        public Unit SelectedUnit
        {
            get { return this.selectedUnit; }
            set { this.selectedUnit = value; }
        }

        public UnitFormEdit()
        {
            InitializeComponent();

            this.SetUp();
        }

        public UnitFormEdit(Unit unit)
        {
            InitializeComponent();

            this.selectedUnit = unit;
            this.SetUp();
            this.LoadData();
        }

        private void SetUp()
        {
            this.unitRepository = Program.Container.Resolve<IRepository<Unit>>();
        }

        private void LoadData()
        {
            if (this.selectedUnit != null)
            {
                this.txtUnitName.Text = this.selectedUnit.Name;
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            bool isCreating = ((this.selectedUnit == null) || (this.selectedUnit.Id <= 0));
            if (AppHelper<Unit>.IsExists(Unit.Properties.Name, this.txtUnitName.Name, isCreating))
            {
                this.txtUnitName.Focus();
            }
            else
            {
                this.AssignUnitData();
                this.DialogResult = DialogResult.OK;
            }
        }

        private void AssignUnitData()
        {
            try
            {
                if (this.selectedUnit == null)
                {
                    this.selectedUnit = new Unit
                    {
                        CreatedDate = DateTime.Now,
                        Creator = Program.SessionData.ActiveAccount,
                    };
                }
                else
                {
                    this.selectedUnit.LastModifiedDate = DateTime.Now;
                    this.selectedUnit.LastModifier = Program.SessionData.ActiveAccount;
                }

                this.selectedUnit.Name = this.txtUnitName.Text;
            }
            catch (Exception ex)
            {
                _logger.Error("Could not save unit", ex);
            }
        }
    }
}
